package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginFilter implements Filter {
    //@Autowired
    //private JedisPool jedisPool;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //Jedis jedis = jedisPool.getResource();
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setContentType("text/html;charset=UTF-8");
        //获得uri路径
        String uri = request.getRequestURI();
        String uriName = uri.substring(uri.lastIndexOf("/"));
        //如果uri路径指向登录界面,则无条件放行
        if ("/".equals(uriName)
                || "/login".equals(uriName)
                || "/login.html".equals(uriName)
                || "/login4Password.html".equals(uriName)) {
            chain.doFilter(request, response);
        }else {
            if ((request.getSession().getAttribute("loginInfo")==null)) {
                response.getWriter().println("<script>alert('您还未登陆请先登陆！')</script>");
                //request.getRequestDispatcher(request.getContextPath()+"/pages/login.html").forward(request,response);
                response.setHeader("Refresh", "0,URL=" +request.getContextPath()+ "/pages/login.html");
                return;
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
